//
//  MessageViewController.m
//  TengyunStation
//
//  Created by Johnny on 15/9/16.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "MessageViewController.h"
#import "MessageListViewController.h"
#import "SocketRequest.h"
#import "Singleton.h"
#import "MessageCell.h"

@interface MessageViewController ()<SocketRequestDelegate> {
    SocketRequest *_socketRequest;
    NSMutableArray *_messageList;
}

@end

@implementation MessageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _socketRequest = [[SocketRequest alloc] initWithSocketRequestDelegate:self];
        _messageList = [NSMutableArray arrayWithCapacity:1];
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if ([Singleton shareInstance].statisticsCount.noReadCount > 0) {
        self.title = [NSString stringWithFormat:@"消息(%d)",[Singleton shareInstance].statisticsCount.noReadCount];
    } else {
        self.title = @"消息";
    }
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 0.1)];
    headerView.backgroundColor = [UIColor clearColor];
    self.tableView.tableHeaderView = headerView;
    [self getMessageFromSqlite];
    [self handelNetWorkMethod];
}

- (void)getMessageFromSqlite {
    NSString *sql = [NSString stringWithFormat:@"ORDER BY mesasgeType ASC"];
    NSArray *array = [Message findByCriteria:sql];
    [_messageList addObjectsFromArray:array];
    [self.tableView reloadData];
    if (_messageList.count > 0) {
        [ToastActivity makeActivity:@"正在加载中..." InView:self.view];
    }
    [self getMessageSocket];
}

- (void)getMessageSocket {
    if (_messageList.count <= 0) {
        [self.tableView makeLoading];
    } else {
        [self.tableView makeNone];
    }
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STM1"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.userId] length:64];
    [_socketRequest addSocketData:mutableData SocketTag:1];
}

#pragma mark SocketRequestDelegate
- (void)socket:(GCDAsyncSocket *)socket Code:(NSString *)code Msg:(NSString *)msg Data:(NSData *)data {
    [self.tableView endRefreshPullTableView];
    [ToastActivity dismissInView:self.view];
    if ([code isEqualToString:SuccessSocket]) {
        NSString *content = [SocketMethod stringDecryHexData:data];
        DLog(@"%@",content);
        NSArray *array = [content componentsSeparatedByString:@"|"];
        [_messageList removeAllObjects];
        [Message clearTable];
        for (NSString *string in array) {
            if (string.length > 0) {
                Message *message = [[Message alloc] initWithString:string];
                [message saveOrUpdate];
                [_messageList addObject:message];
            }
        }
        if (_messageList.count <= 0) {
            [self.tableView makeTip:@"无消息数据"];
        } else {
            self.tableView.backgroundView = nil;
            [self.tableView reloadData];
        }
    } else {
        if (_messageList.count <= 0) {
            [self.tableView makeTip:msg];
        } else {
            [DSToast showText:msg InView:self.view];
        }
    }
}

- (void)socket:(GCDAsyncSocket *)socket Msg:(NSString *)msg {
    [self.tableView endRefreshPullTableView];
    [ToastActivity dismissInView:self.view];
    if (_messageList.count <= 0) {
        [self.tableView makeTip:msg Title:@"重新加载" Target:self Selector:@selector(getMessageSocket)];
    }
    [DSToast showText:msg InView:self.view];
}

#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _messageList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 64.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIndentifier = @"MessageCell";
    MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"MessageCell" owner:self options:nil] lastObject];
    }
    Message *message = [_messageList objectAtIndex:indexPath.row];
    [cell reloadMessageCell:message];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    Message *message = [_messageList objectAtIndex:indexPath.row];
    if ([message.mesasgeType isEqualToString:@"00"]) {
        [Singleton shareInstance].statisticsCount.noReadCount -= [Singleton shareInstance].statisticsCount.systemMessageCount;
        [Singleton shareInstance].statisticsCount.systemMessageCount = 0;
    } else if ([message.mesasgeType isEqualToString:@"01"]) {
        [Singleton shareInstance].statisticsCount.noReadCount -= [Singleton shareInstance].statisticsCount.businessMessageCount;
        [Singleton shareInstance].statisticsCount.businessMessageCount = 0;
    } else if ([message.mesasgeType isEqualToString:@"02"]) {
        [Singleton shareInstance].statisticsCount.noReadCount -= [Singleton shareInstance].statisticsCount.personalMessageCount;
        [Singleton shareInstance].statisticsCount.personalMessageCount = 0;
    } else if ([message.mesasgeType isEqualToString:@"04"]) {
        [Singleton shareInstance].statisticsCount.noReadCount -= [Singleton shareInstance].statisticsCount.receiveMessageCount;
        [Singleton shareInstance].statisticsCount.receiveMessageCount = 0;
    }
    if ([Singleton shareInstance].statisticsCount.noReadCount > 0) {
        self.title = [NSString stringWithFormat:@"消息(%d)",[Singleton shareInstance].statisticsCount.noReadCount];
    } else {
        self.title = @"消息";
    }
    MessageListViewController *messageLVC = [[MessageListViewController alloc] initWithNibName:@"MessageListViewController" bundle:nil];
    messageLVC.messageType = message.mesasgeType;
    [self.navigationController pushViewController:messageLVC animated:YES];
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.tableView pullScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self.tableView pullscrollViewDidEndDragging:scrollView];
}

#pragma mark PullTableViewDelegate
- (void)startRefreshHeaderView {
    [self getMessageSocket];
}

- (void)dealloc {
    _socketRequest = nil;
    _messageList = nil;
}

@end
